<template>
  <el-drawer
    v-model="open"
    :title="$props.title"
    :with-header="true"
    size="50%"
    class="course-drawer"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="closeW"
  >
    <div class="content">
      <el-form ref="csRef" :model="form" label-width="auto">
        <el-form-item
          label="课程"
          prop="courseId"
          :rules="[
            {
              required: true,
              message: '请选择课程',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            style="width: 320px"
            v-model="form.courseId"
            placeholder="课程"
            clearable
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.state === '1' ? item.name + '(已停用)' : item.name"
              :value="item.id"
              :disabled="item.state === '1'"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="班级"
          prop="classId"
          :rules="[
            {
              required: true,
              message: '请选择班级',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            style="width: 320px"
            v-model="form.classId"
            placeholder="班级"
            clearable
            disabled
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <template v-if="$props.from === 'rollCall'">
          <el-form-item
            label="上课日期"
            prop="classDate"
            :rules="[
              {
                required: true,
                message: '请选择上课日期',
                trigger: 'change',
              },
            ]"
          >
            <el-date-picker
              style="width: 140px"
              v-model="form.classDate"
              class="mr-4"
              placeholder="上课日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="上课时间"
            prop="classStartTime"
            :rules="[
              {
                required: true,
                message: '请选择上课时间',
                trigger: 'change',
              },
            ]"
          >
            <el-time-select
              style="width: 140px"
              v-model="form.classStartTime"
              :max-time="form.classEndTime"
              class="mr-4"
              placeholder="开始时间"
              start="00:00"
              step="00:05"
              end="23:55"
            />

            <div style="text-align: center; width: 40px; display: inline-block">
              ~
            </div>
            <el-time-select
              style="width: 140px"
              v-model="form.classEndTime"
              :min-time="form.classStartTime"
              placeholder="结束时间"
              start="00:00"
              step="00:05"
              end="23:55"
            />
          </el-form-item>
        </template>
        <el-form-item
          label="主班老师"
          prop="teacher"
          :rules="[
            {
              required: true,
              message: '请选择主班老师',
              trigger: 'change',
            },
          ]"
        >
          <el-select
            style="width: 320px"
            v-model="form.teacher"
            placeholder="主班老师"
            clearable
          >
            <el-option
              v-for="item in teacherList"
              :key="item.value"
              :label="
                !item.isJob
                  ? item.label + '(已离职)'
                  : !item.isTeacher
                  ? item.label + '(非授课)'
                  : item.label
              "
              :value="item.value"
              :disabled="!item.isJob || !item.isTeacher"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="助教老师" prop="assistantArr">
          <el-select
            style="width: 320px"
            v-model="form.assistantArr"
            placeholder="助教老师"
            multiple
            clearable
          >
            <el-option
              v-for="item in teacherList"
              :key="item.value"
              :label="
                !item.isJob
                  ? item.label + '(已离职)'
                  : !item.isTeacher
                  ? item.label + '(非授课)'
                  : item.label
              "
              :value="item.value"
              :disabled="!item.isJob || !item.isTeacher"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上课教室" prop="classRoom">
          <el-select
            style="width: 320px"
            v-model="form.classRoom"
            placeholder="上课教室"
            clearable
          >
            <el-option
              v-for="item in roomList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button
            style="padding: 0 10px"
            type="primary"
            link
            @click="openRoom = true"
          >
            新增
          </el-button>
        </el-form-item>
        <el-form-item
          v-if="$props.from === 'schedule'"
          label="授课课时"
          prop="classHour"
          :rules="[
            {
              required: true,
              message: '请填写授课课时',
              trigger: 'blur',
            },
          ]"
        >
          <el-input-number v-model="form.classHour" :min="0" />
        </el-form-item>
        <el-form-item label="上课内容" prop="description">
          <el-input
            type="textarea"
            v-model="form.description"
            placeholder="请输入上课内容"
            style="width: 500px"
          />
        </el-form-item>

        <el-form-item label="排课方式" prop="type" disabled v-show="false">
          <el-radio-group v-model="form.type">
            <el-radio value="1">规则排课</el-radio>
            <el-radio value="2">日历排课</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="$props.from === 'schedule'">
          <el-form-item
            label="日期范围"
            prop="range"
            :rules="[
              {
                required: true,
                message: '请选择日期范围',
                trigger: 'change',
              },
            ]"
          >
            <el-col :span="14">
              <el-date-picker
                v-model="form.range"
                type="daterange"
                unlink-panels
                range-separator="到"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts"
                :size="size"
                @change="dataRangeChange"
                value-format="YYYY-MM-DD"
              />
            </el-col>
            <el-tooltip
              class="box-item"
              effect="light"
              content="新建排班：当开始日期小于当天时，仅从当天开始排班，不做历史排班；编辑排班：仅更新当天及之后的排班记录，当天之前已生成的排班将不受排班编辑影响。"
              placement="top-start"
            >
              <el-icon><Warning /></el-icon>
            </el-tooltip>
          </el-form-item>

          <el-form-item label="考勤方式" prop="excess">
            <el-radio-group v-model="form.excess">
              <el-radio :value="1">计入考勤</el-radio>
              <el-radio :value="0">不计入考勤</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="重复方式" prop="circulateType">
            <el-radio-group
              v-model="form.circulateType"
              @change="circulateTypeChange"
            >
              <el-radio value="1">每天重复</el-radio>
              <el-radio value="2">每周重复</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-table
            class="quotation"
            style="width: 100%"
            max-height="250"
            :data="form.list"
            v-if="form.circulateType === '2'"
          >
            <el-table-column prop="weekNum" label="星期" width="320">
              <template #default="scope">
                <el-form-item
                  :prop="`list.${scope.$index}.weekNum`"
                  :rules="[
                    {
                      required: true,
                      message: '请选择星期',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    v-model="scope.row.weekNum"
                    placeholder="星期"
                    clearable
                  >
                    <el-option
                      v-for="item in weekList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="timeDuration" label="上课时间">
              <template #default="scope">
                <el-row>
                  <el-col :span="11">
                    <el-form-item
                      :prop="`list.${scope.$index}.classStartTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择上课开始时间',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-time-select
                        v-model="scope.row.classStartTime"
                        :max-time="scope.row.classEndTime"
                        class="mr-4"
                        placeholder="开始时间"
                        start="00:00"
                        step="00:05"
                        end="23:55"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2"
                    ><div style="text-align: center">~</div>
                  </el-col>
                  <el-col :span="11">
                    <el-form-item
                      :prop="`list.${scope.$index}.classEndTime`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择上课结束时间',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-time-select
                        v-model="scope.row.classEndTime"
                        :min-time="scope.row.classStartTime"
                        placeholder="结束时间"
                        start="00:00"
                        step="00:05"
                        end="23:55"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <template v-else>
            <el-form-item
              label="上课时间"
              prop="classStartTime"
              :rules="[
                {
                  required: true,
                  message: '请选择上课时间',
                  trigger: 'change',
                },
              ]"
            >
              <el-time-select
                style="width: 140px"
                v-model="form.classStartTime"
                :max-time="form.classEndTime"
                class="mr-4"
                placeholder="开始时间"
                start="00:00"
                step="00:05"
                end="23:55"
              />

              <div
                style="text-align: center; width: 40px; display: inline-block"
              >
                ~
              </div>
              <el-time-select
                style="width: 140px"
                v-model="form.classEndTime"
                :min-time="form.classStartTime"
                placeholder="结束时间"
                start="00:00"
                step="00:05"
                end="23:55"
              />
            </el-form-item>
          </template>
        </template>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="closeW">取消</el-button>
      <el-button type="primary" :loading="loading" @click="submitForm">
        {{ loading ? btn + "中..." : btn }}
      </el-button>
    </template>
  </el-drawer>
  <el-dialog
    v-model="openRoom"
    title="教室设置"
    width="500"
    :before-close="handleClose"
  >
    <el-button @click="handleAddRoom" type="primary"> 添加 </el-button>
    <el-form ref="roomRef" :model="roomForm" label-width="auto">
      <el-table
        class="quotation"
        :data="roomForm.copyRoomList"
        style="width: 100%; margin-top: 20px"
        max-height="400"
      >
        <el-table-column prop="name" label="教室名称">
          <template #default="scope">
            <el-form-item
              :prop="`copyRoomList.${scope.$index}.name`"
              :rules="[
                {
                  required: true,
                  message: '请输入教室名称',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input v-model="scope.row.name"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="handleDeleteRoom(scope.$index)"
              v-if="scope.row.used === '0'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelRoomList()">取消</el-button>
        <el-button type="primary" @click="updateRoomList()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  getTLabelListAPI,
  updateTLabelListAPI,
} from "@/api/registrar/classroom";
import { getPeopleList } from "@/api/studentManagement/index";
import {
  getClassListAPI,
  getRollCallDetailAPI,
  updateOrderInRollCallAPI,
} from "@/api/registrar/class";
import { getCourseListAPI } from "@/api/registrar/course";

import {
  saveScheduleAPI,
  updateScheduleAPI,
  getScheduleDetailAPI,
} from "@/api/registrar/schedule";

const props = defineProps({
  title: {
    type: String,
  },
  // 保存按钮显示名称
  btn: {
    type: String,
  },
  // 是否需要做父组件列表的刷新操作
  refresh: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  courseFilterIds: {
    type: String,
  },
  classId: {
    type: String,
  },
  // 班级类型/授课方式
  isVip: {
    type: String,
  },

  // 父页面来源，默认是排课，来源包括排课schedule、点名rollCall
  from: {
    type: String,
    default: () => {
      return "schedule";
    },
  },
  // ifEdit: {
  //   type: Boolean,
  //   default: () => {
  //     return false;
  //   },
  // },
});

const emits = defineEmits(["refreshPage"]);

const { proxy } = getCurrentInstance();

const loading = ref(false);
const open = ref(false);
const openRoom = ref(false);

const shortcuts = ref([
  {
    text: "1年后结束",
    value: () => {
      const end = new Date();
      const start = new Date();
      end.setFullYear(end.getFullYear() + 1);
      return [start, end];
    },
  },
  {
    text: "3年后结束",
    value: () => {
      const end = new Date();
      const start = new Date();
      end.setFullYear(end.getFullYear() + 3);
      return [start, end];
    },
  },
  {
    text: "5年后结束",
    value: () => {
      const end = new Date();
      const start = new Date();
      end.setFullYear(end.getFullYear() + 5);
      return [start, end];
    },
  },
]);

const weekList = ref([
  { label: "周一", value: 1 },
  { label: "周二", value: 2 },
  { label: "周三", value: 3 },
  { label: "周四", value: 4 },
  { label: "周五", value: 5 },
  { label: "周六", value: 6 },
  { label: "周日", value: 7 },
]);

const data = reactive({
  form: {
    courseId: undefined,
    classId: props.classId,
    classHour: 1,
    circulateType: "1",
    type: "1",
    excess: 1,
    classStartTime: null,
    classEndTime: null,
    teacher: null,
    assistant: null, // "23,55"
    assistantArr: [],
    description: "",
    classRoom: "",
    range: [], // ["2024-10-10", "2026-12-09"]
    startTime: null,
    endTime: null,
    weekNum: 1, // Integer。每周排课时，周几上课
    list: [
      {
        weekNum: null,
        classStartTime: null,
        classEndTime: null,
      },
    ],
  },
  roomForm: {
    copyRoomList: [],
  },
});

const { form, roomForm } = toRefs(data);
const roomList = ref([]);
const teacherList = ref([]);
const courseList = ref([]);
const classList = ref([]);

// 监听------------------------------------------------------------------------------------------------------------
watch(
  () => form.value.assistantArr,
  (n, o) => {
    if (!n) n = [];
    form.value.assistant = n.join(",");
  }
);

// watch(
//   () => props.courseFilterIds,
//   (n, o) => {
//     getCourseFilterList();
//   }
// );

// 方法-------------------------------------------------------------------------------------------------------------

// 获取教师列表
function getTeacherList() {
  loading.value = true;
  getPeopleList({ isTeach: 1 }).then((response) => {
    teacherList.value = response.data;
    loading.value = false;
  });
}

// 教室
function getRoomList() {
  loading.value = true;
  getTLabelListAPI({ lableType: "class_room" }).then((response) => {
    roomList.value = response.data;
    roomForm.value.copyRoomList = [...response.data];
    loading.value = false;
  });
}

// 班级
function getClassList() {
  loading.value = true;
  getClassListAPI({ pageSize: 9999, pageNum: 1, isVip: props.isVip }).then(
    (response) => {
      classList.value = response.rows;
      loading.value = false;
    }
  );
}

// 关联课程
function getCourseFilterList() {
  getCourseListAPI({
    pageSize: 9999,
    pageNum: 1,
    //state: "0",
    open: "1", //不包含公开课
    idsStr: props.courseFilterIds,
    lessonType: props.isVip,
  }).then((response) => {
    courseList.value = response.rows;
    loading.value = false;
  });
}

function updateRoomList() {
  proxy.$refs["roomRef"].validate((valid) => {
    if (valid) {
      loading.value = true;
      updateTLabelListAPI(roomForm.value.copyRoomList).then(() => {
        loading.value = false;
        openRoom.value = false;
        getRoomList();
      });
    } else {
      proxy.$modal.msgError("教室名称不可为空，请检查后再提交");
    }
  });
}

function cancelRoomList() {
  roomForm.value.copyRoomList = [...roomList.value];
  openRoom.value = false;
}

function handleAddRoom() {
  roomForm.value.copyRoomList.push({
    id: undefined,
    name: "",
    lableType: "class_room",
    used: "0",
  });
}

function handleDeleteRoom(index) {
  roomForm.value.copyRoomList.splice(index, 1);
}

function circulateTypeChange(value) {
  form.value.list = [
    { classStartTime: null, classEndTime: null, weekNum: null },
  ];
  form.value.classStartTime = null;
  form.value.classEndTime = null;
}

function dataRangeChange(event) {
  form.value.range = event;
  form.value.startTime = event ? event[0] : null;
  form.value.endTime = event ? event[1] : null;
}

// 排课保存或更改
function submitForm() {
  if (props.from === "schedule" && form.value.circulateType === "2") {
    const { classStartTime, classEndTime, weekNum } = form.value.list[0];
    form.value.classStartTime = classStartTime;
    form.value.classEndTime = classEndTime;
    form.value.weekNum = weekNum;
  }
  proxy.$refs["csRef"].validate((valid) => {
    if (valid) {
      if (props.from === "schedule") {
        if (form.value.id != undefined) {
          updateScheduleAPI(form.value).then((response) => {
            proxy.$modal.msgSuccess("编辑成功");
            closeW();
            refreshParent();
          });
        } else {
          saveScheduleAPI(form.value).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            closeW();
            refreshParent();
          });
        }
      } else if (props.from === "rollCall") {
        updateOrderInRollCallAPI(form.value).then((response) => {
          proxy.$modal.msgSuccess("编辑成功");
          closeW();
          refreshParent();
        });
      }
    } else {
      proxy.$modal.msgError("表单校验未通过，请重新检查提交内容");
    }
  });
}

// 排课信息  一键排课  调用
function getScheduleDetail(id) {
  initPicker();
  getScheduleDetailAPI({ id: id }).then((response) => {
    form.value = response.data;
    form.value.courseId = form.value.courseId.toString();
    form.value.classId = form.value.classId.toString();
    form.value.circulateType =
      form.value.circulateType && form.value.circulateType.toString();
    const { weekNum, classStartTime, classEndTime } = form.value;
    form.value.list = [{ weekNum, classStartTime, classEndTime }];
    form.value.range = [form.value.startTime, form.value.endTime];
    open.value = true;
  });
}

// 点名情况 查看详情 编辑课次 调用
function getScheduleDetailInRollCall(id) {
  initPicker();
  getRollCallDetailAPI({ id }).then((response) => {
    form.value = response.data;
    form.value.courseId = form.value.courseId.toString();
    form.value.classId = form.value.classId.toString();
    form.value.classRoom = form.value.classRoom
      ? parseInt(form.value.classRoom)
      : null;
    form.value.range = [form.value.startTime, form.value.endTime];
    open.value = true;
  });
}

function refreshParent() {
  if (props.refresh) emits("refreshPage");
}

function closeW() {
  open.value = false;
  reset();
}
function reset() {
  form.value = {
    courseId: undefined,
    classId: props.classId,
    classHour: 1,
    circulateType: "1",
    type: "1",
    excess: 1,
    classStartTime: null,
    classEndTime: null,
    teacher: null,
    assistant: null, // "23,55"
    assistantArr: [],
    description: "",
    classRoom: "",
    range: [], // ["2024-10-10", "2026-12-09"]
    startTime: null,
    endTime: null,
    weekNum: null, // Integer。每周排课时，周几上课
    list: [
      {
        weekNum: null,
        classStartTime: null,
        classEndTime: null,
      },
    ],
  };
  proxy.resetForm("csRef");
}

// 清空form
function openW() {
  initPicker();
  open.value = true;
}

function initPicker() {
  getCourseFilterList();
  getRoomList();
  getClassList();
  getTeacherList();
}
//调用---------------------------------------------------------------------------------------------------------------

defineExpose({ openW, getScheduleDetail, getScheduleDetailInRollCall }); // 用于父组件调用
</script>

<style lang="scss" scoped></style>
